package com.busApp;

import org.apache.cordova.api.Plugin;
import org.apache.cordova.api.PluginResult;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;

public class BdLocation extends Plugin {
	public static final String ACTION = "location";
	private LocationClient mLocationClient = null;
	private JSONObject jsonObj = new JSONObject();
	private static PluginResult result = null;

	@Override
	public PluginResult execute(String action, JSONArray data, String callbackId) {
		if (action.equals(ACTION)) {
			try {
				cordova.getActivity().runOnUiThread(new RunnableLoc());

			} catch (Exception e) {
			}

		} else {
			mLocationClient.stop();
			if(result == null)
				result = new PluginResult(PluginResult.Status.OK);
		}
		while (result == null) {
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {

				e.printStackTrace();
			}
		}
		return result;
	}

	@Override
	public void onDestroy() {
		if (mLocationClient != null && mLocationClient.isStarted()) {
			mLocationClient.stop();
			mLocationClient = null;
		}
		super.onDestroy();
	}

	class RunnableLoc implements Runnable {
		public void run() {
			mLocationClient = new LocationClient(cordova.getActivity());
			LocationClientOption option = new LocationClientOption();
			option.setOpenGps(true);
			option.setCoorType("bd09ll");
			option.setProdName("BaiduLoc");
			option.setScanSpan(60000);
			mLocationClient.setLocOption(option);
			mLocationClient.registerLocationListener(new BDLocationListener() {

				public void onReceiveLocation(BDLocation location) {
					if (location == null) {
						return;
					}
					StringBuffer sb = new StringBuffer(256);
					if (location.getLocType() == BDLocation.TypeGpsLocation) { // GPS情况
						sb.append("\nSpeed : ");
						sb.append(location.getSpeed());
						sb.append("\nSatellite : ");
						sb.append(location.getSatelliteNumber());
					} else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
						sb.append("\nAddress : ");
						sb.append(location.getAddrStr());
						try {
							jsonObj.put("Longitude", location.getLongitude());
							jsonObj.put("Latitude", location.getLatitude());
							result = new PluginResult(PluginResult.Status.OK,
									jsonObj);
						} catch (JSONException e) {
							e.printStackTrace();
						}
					}
				}
			});
			mLocationClient.start();
		}

	}

}
